<template>
  <div class="chat-container">
    <div class="message-area" ref="messageArea">
      <div v-for="(msg, index) in messages" :key="index" class="message-wrapper">
        <div :class="['message', msg.role]">
          <div class="message-header">
            <span class="sender">{{ msg.role === 'user' ? '你' : 'AI助手' }}</span>
            <span class="time">{{ formatTime(msg.timestamp) }}</span>
          </div>
          <div class="message-content">{{ msg.content }}</div>
        </div>
      </div>
    </div>
    <div class="input-area">
      <input
          v-model="inputMessage"
          @keyup.enter="sendMessage"
          placeholder="输入消息..."
      />
      <button @click="sendMessage" :disabled="!inputMessage.trim()">发送</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { getToken } from "@/utils/storage.js";

export default {
  name: "ChatWindow",
  data() {
    return {
      inputMessage: '',
      messages: []
    };
  },
  created() {
    this.loadMessages();
  },
  methods: {
    async sendMessage() {
      if (!this.inputMessage.trim()) return;

      // 添加用户消息
      const userMsg = {
        role: 'user',
        content: this.inputMessage,
        timestamp: new Date()
      };
      this.messages.push(userMsg);
      this.saveMessages();

      // 清空输入框
      const messageToSend = this.inputMessage;
      this.inputMessage = '';

      try {
        // 发送请求
        const response = await axios.post('http://localhost:9282/chat', {
          message: messageToSend
        }, {
          headers: {
            token: getToken()
          }
        });

        // 添加AI回复
        const aiMsg = {
          role: 'assistant',
          content: response.data.choices[0].message.content,
          timestamp: new Date()
        };
        this.messages.push(aiMsg);
        this.saveMessages();

      } catch (error) {
        console.error('请求失败:', error);
        // 添加错误提示消息
        const errorMsg = {
          role: 'system',
          content: '消息发送失败，请重试',
          timestamp: new Date()
        };
        this.messages.push(errorMsg);
        this.saveMessages();
      }

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },

    scrollToBottom() {
      const container = this.$refs.messageArea;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },

    formatTime(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getHours()}:${d.getMinutes().toString().padStart(2, '0')}`;
    },

    saveMessages() {
      localStorage.setItem('chatMessages', JSON.stringify(this.messages));
    },

    loadMessages() {
      const saved = localStorage.getItem('chatMessages');
      if (saved) {
        try {
          this.messages = JSON.parse(saved);
          // 转换时间字符串为Date对象
          this.messages.forEach(msg => {
            if (typeof msg.timestamp === 'string') {
              msg.timestamp = new Date(msg.timestamp);
            }
          });
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        } catch (e) {
          console.error('加载消息历史失败', e);
        }
      }
    }
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  max-width: 800px;
  margin: 0 auto;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.message-area {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message-wrapper {
  margin-bottom: 12px;
}

.message {
  padding: 12px 16px;
  border-radius: 8px;
  max-width: 80%;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.message.user {
  margin-left: auto;
  background-color: #e3f2fd;
  border-bottom-right-radius: 0;
}

.message.assistant {
  margin-right: auto;
  background-color: #ffffff;
  border-bottom-left-radius: 0;
}

.message.system {
  margin: 0 auto;
  background-color: #f5f5f5;
  text-align: center;
  max-width: 100%;
  font-size: 0.9em;
  color: #666;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 0.8em;
  color: #666;
}

.sender {
  font-weight: bold;
}

.time {
  opacity: 0.8;
}

.message-content {
  word-break: break-word;
  white-space: pre-wrap;
}

.input-area {
  display: flex;
  padding: 12px;
  background-color: #fff;
  border-top: 1px solid #e0e0e0;
}

.input-area input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 8px;
  outline: none;
}

.input-area input:focus {
  border-color: #4a90e2;
}

.input-area button {
  padding: 10px 16px;
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.input-area button:hover {
  background-color: #3a7bc8;
}

.input-area button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>